/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.property.service.impl;

import me.zhengjie.modules.property.domain.Money;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.property.repository.MoneyRepository;
import me.zhengjie.modules.property.service.MoneyService;
import me.zhengjie.modules.property.service.dto.MoneyDto;
import me.zhengjie.modules.property.service.dto.MoneyQueryCriteria;
import me.zhengjie.modules.property.service.mapstruct.MoneyMapper;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author yyj
* @date 2022-07-02
**/
@Service
@RequiredArgsConstructor
public class MoneyServiceImpl implements MoneyService {

    private final MoneyRepository moneyRepository;
    private final MoneyMapper moneyMapper;

    @Override
    public Map<String,Object> queryAll(MoneyQueryCriteria criteria, Pageable pageable){
        Page<Money> page = moneyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(moneyMapper::toDto));
    }

    @Override
    public List<MoneyDto> queryAll(MoneyQueryCriteria criteria){
        Sort sort = Sort.by(Sort.Direction.ASC, "createTime");
        return moneyMapper.toDto(moneyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),sort));
    }

    @Override
    @Transactional
    public MoneyDto findById(Integer id) {
        Money money = moneyRepository.findById(id).orElseGet(Money::new);
        ValidationUtil.isNull(money.getId(),"Money","id",id);
        return moneyMapper.toDto(money);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MoneyDto create(Money resources) {
        return moneyMapper.toDto(moneyRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Money resources) {
        Money money = moneyRepository.findById(resources.getId()).orElseGet(Money::new);
        ValidationUtil.isNull( money.getId(),"Money","id",resources.getId());
        money.copy(resources);
        moneyRepository.save(money);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            moneyRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<MoneyDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (MoneyDto money : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("创建时间", money.getCreateTime());
            map.put("银行卡", money.getCard());
            map.put("微信", money.getWx());
            map.put("支付宝", money.getPay());
            map.put("借", money.getLend());
            map.put("证券", money.getBond());
            map.put("详情", money.getDetail());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Boolean getNewCreateTime() {

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        String dateString = formatter.format(currentTime);
        List<String> moneyList = moneyRepository.getMoneyList();

        boolean flag = moneyList.contains(dateString);

        return flag;
    }

    @Override
    public Map<String, Object> getLineChart() {
        HashMap<String, Object> map = new HashMap<>();
        List<Timestamp> moneyList = queryAll(new MoneyQueryCriteria()).stream().map(MoneyDto::getCreateTime).collect(Collectors.toList());
        moneyList.remove(moneyList.size()-1);
        List<Money> allData = moneyRepository.findAll();
        List<String> card = new ArrayList<>();
        List<String> wx = new ArrayList<>();
        List<String> pay = new ArrayList<>();
        List<String> lend = new ArrayList<>();
        List<String> bond = new ArrayList<>();
        List<Integer> sum = new ArrayList<>();
        moneyList.forEach(res->{
            Money money = allData.stream().filter(e -> e.getCreateTime().equals(res)).findFirst().get();
            card.add(money.getCard());
            wx.add(money.getWx());
            pay.add(money.getPay());
            lend.add(money.getLend());
            bond.add(money.getBond());
            sum.add(Integer.parseInt(money.getCard())+Integer.parseInt(money.getWx())+Integer.parseInt(money.getPay())+Integer.parseInt(money.getLend())+Integer.parseInt(money.getBond()));

        });
        Map<String, Object> yAxis = new HashMap<>();
        yAxis.put("card",card);
        yAxis.put("wx",wx);
        yAxis.put("pay",pay);
        yAxis.put("lend",lend);
        yAxis.put("bond",bond);
        yAxis.put("sum",sum);

        map.put("xAxis",moneyList);
        map.put("yAxis",yAxis);
        return map;
    }
}